﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace RenameSubtitles
{
    public class RenameSubtitlesJob
    {
        public delegate bool AskUserConfirmationDelegate(string folder, List<Item> renameItems);
        public class Item
        {
            public Item(string oldFileName, string newFileName)
            {
                this.oldFilename = oldFileName;
                this.newFilename = newFileName;
            }
            public string oldFilename, newFilename;
        }
        public class ChapterId
        {
            public int Season, Chapter;
            public ChapterId()
            {
                Season = -1; Chapter = -1;
            }
            public ChapterId(int season, int chapter)
            {
                Season = season;
                Chapter = chapter;
            }
            public override bool Equals(object obj)
            {
                if (obj is ChapterId)
                {
                    ChapterId other = (ChapterId)obj;
                    return Season == other.Season && Chapter == other.Chapter;
                }
                else
                    return false;
            }
            public bool ParseString(string cadena)
            {
                // TIPO 1x14
                Match match = format1.Match(cadena);
                if (match.Success)
                {
                    int separatorIndex;
                    string chapterId = match.Value.ToLower();
                    if ((separatorIndex = chapterId.IndexOf("x")) > -1)
                    {
                        Season = int.Parse(chapterId.Substring(0, separatorIndex));
                        Chapter = int.Parse(chapterId.Substring(separatorIndex + 1));
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                // Tipo S03E08
                match = format2.Match(cadena);
                if (match.Success)
                {
                    int separatorIndex;
                    string chapterId = match.Value.ToLower();
                    if ((separatorIndex = chapterId.IndexOf("e")) > -1)
                    {
                        Season = int.Parse(chapterId.Substring(1, separatorIndex -1));
                        Chapter = int.Parse(chapterId.Substring(separatorIndex + 1));
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }

                // Tipo 212
                match = format3.Match(cadena);
                if (match.Success)
                {

                    string chapterId = match.Value.ToLower();
                    Season = int.Parse(chapterId.Substring(0, 1));
                    Chapter = int.Parse(chapterId.Substring(1));
                    return true;

                }
                // Tipo no reconocido
                return false;
            }
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
            private static Regex format1 = new Regex(@"\dx\d\d", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            private static Regex format2 = new Regex(@"S\d\dE\d\d", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            private static Regex format3 = new Regex(@"\d\d\d", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }


        private string rootPath;
        private string path;
        bool recursive = false;
        bool moveFiles;
        private List<string> aviFiles = new List<string>();
        private List<string> subFiles = new List<string>();
        private List<Item> renameItems= new List<Item>();
        private LogFile log = null;
        private List<string> copiedFiles = new List<string>();
        private Regex regex = new Regex(@"(\dx\d\d)|(S\d\dE\d\d)", RegexOptions.Compiled|RegexOptions.IgnoreCase|RegexOptions.Singleline);
        private StringTable ST = new StringTable();

        private AskUserConfirmationDelegate AskUserConfirmationFun = null;
        public RenameSubtitlesJob(string path, bool moveFiles, bool recursive)
        {
            this.recursive = recursive;
            //log = new LogFile(path + "\\"+ "RenameSubtitlesOutput.txt");
            log = new LogFile();
            this.rootPath = path;
            this.moveFiles = moveFiles;
        }
        public RenameSubtitlesJob(string path, bool moveFiles, bool recursive, AskUserConfirmationDelegate fun)
        {
            AskUserConfirmationFun = fun;
            this.recursive = recursive;
            //log = new LogFile(path + "\\"+ "RenameSubtitlesOutput.txt");
            log = new LogFile();
            this.rootPath = path;
            this.moveFiles = moveFiles;
        }

        internal void Start()
        {
            try
            {
                
                ProcessFolder(rootPath);
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                log.Dispose();
            }

        }

        private void ProcessFolder(string folder)
        {
            CleanList();
            path = folder;
            LoadAviFiles(path);
            LoadSubtitles(path);
            GenerateRenameItems();
            if (AskUserConfirmation() == true)
            {
                DoRenameItems();
                DeleteSourceSubtitles();
            }
            if (recursive)
            {
                DirectoryInfo folderInfo = new DirectoryInfo(folder);
                DirectoryInfo[] childs = folderInfo.GetDirectories();
                foreach (DirectoryInfo child in childs)
                {
                    ProcessFolder(child.FullName);
                }
            }
            
        }

        private void CleanList()
        {
            aviFiles.Clear();
            subFiles.Clear();
            renameItems.Clear();
            copiedFiles.Clear();
        }

        
        private bool AskUserConfirmation()
        {

            if (AskUserConfirmationFun != null)
            {
                return AskUserConfirmationFun(path, renameItems);
            }
            PrintRenameItems();
            if (renameItems.Count > 0)
            {
                Console.WriteLine(ST.Get(TEXTO.CONFIRM));
                string read = Console.ReadLine();
                if (read.Equals("y", StringComparison.CurrentCultureIgnoreCase))
                    return true;
                else
                    return false;
            }
            else
            {
                Console.WriteLine(ST.Get(TEXTO.NOFILES));
                Console.WriteLine();
                return false;
            }
        }

        private void PrintRenameItems()
        {
            Console.WriteLine(ST.Get(TEXTO.HEADER1)+ path);
            Console.WriteLine("============================================================");
            
            foreach (Item item in renameItems)
            {
                Console.WriteLine( ST.Get(TEXTO.INFORME1) , item.oldFilename.Replace(path + "\\", ""), item.newFilename.Replace(path + "\\", ""));
            }
            
            
        }

        private void DoRenameItems()
        {
            foreach (Item item in renameItems)
            {
                try
                {
                    File.Copy(item.oldFilename, item.newFilename);
                    copiedFiles.Add(item.oldFilename);
                }
                catch (Exception e)
                {
                    log.WriteLine("Error al copiar {0}. {1}", item.oldFilename, e.Message);
                }
            }
        }

        

        public void DeleteSourceSubtitles()
        {
            foreach (string file in copiedFiles)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }



        private void GenerateRenameItems()
        {

            foreach (string aviFile in aviFiles)
            {
                string subFile = FindSubtitle(aviFile);
                if (subFile != null)
                {
                    AddRenameItemFor(subFile, aviFile);
                }
            }
        }

        private void AddRenameItemFor(string subFile, string aviFile)
        {
            try
            {
                FileInfo subFileInfo = new FileInfo(subFile);
                FileInfo aviFileInfo = new FileInfo(aviFile);
                string destination = aviFileInfo.DirectoryName + "\\" + aviFileInfo.Name.Substring(0,(int)aviFileInfo.Name.Length - 4) + subFileInfo.Extension;

                if (File.Exists(destination))
                {
                    log.WriteLine("Origen: {0}; Destino: {1}. Ya existe previamente", subFile, destination);
                }
                else
                {
                    log.WriteLine("Origen: {0}; Destino: {1}", subFile, destination);
                    renameItems.Add(new Item(subFile, destination));
                    //File.Copy(subFile, destination);
                    //copiedFiles.Add(subFile);
                }

            }
            catch (Exception e)
            {
                log.WriteLine("Error al copiar {0}. {1}", subFile, e.Message);
            }
        }

        private string FindSubtitle(string aviFile)
        {
            ChapterId chapterId= new ChapterId();
            if (!chapterId.ParseString(aviFile))
            {
                return null;
            }

            foreach (string subFile in subFiles)
            {
                ChapterId subtitleChapterId = new ChapterId();
                if (subtitleChapterId.ParseString(subFile))
                {
                    if (subtitleChapterId.Equals(chapterId))
                        return subFile;
                }
            }
            log.WriteLine("Subtitulo de {0} no encontrado", aviFile);
            return null;
        }

        private string ConvertChapterId(string chapterId)
        {
            int separatorIndex=-1;
            if ((separatorIndex = chapterId.IndexOfAny("xX".ToCharArray())) > -1)
            {
                string text = "S" + (separatorIndex<2?"0":"") +chapterId.Substring(0, separatorIndex) + "E" +chapterId.Substring(separatorIndex + 1);
                return text;
            }
            else
            {
                separatorIndex = chapterId.IndexOfAny("eE".ToCharArray());
                string text = chapterId.Substring(1, separatorIndex -1).TrimStart('0') + "x" + chapterId.Substring(separatorIndex + 1);
                return text;
                
            }
        }

        /// <summary>
        /// Fills subFiles with the fullpath of the captions files in searchPath
        /// </summary>
        private void LoadSubtitles(string searchPath)
        {
            FillList(subFiles, path, "*.srt");
            FillList(subFiles, path, "*.sub");
        }

        /// <summary>
        /// Fills aviFiles with the fullpath of the avi files in searchPath
        /// </summary>
        private void LoadAviFiles(string searchPath)
        {
            FillList(aviFiles, searchPath, "*.avi");
            FillList(aviFiles, searchPath, "*.mkv");
            FillList(aviFiles, searchPath, "*.mp4");
        }

        private void FillList(List<string> fileList, string path, string pattern)
        {
            fileList.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly));
        }

        internal void Test()
        {
            ConvertChapterId("2x10");
            ConvertChapterId("12x10");
            ConvertChapterId("S2E01");
            ConvertChapterId("S02E01");
            ConvertChapterId("S12E01");

            FindSubtitle("pepito de los - 1x03 [dsfdfgdg](jjdhfjdf).avi");
            FindSubtitle("True Blood S01E10 XviD VOSTFR --Antoine 4011-- i");
        }
    }
}

